<template>
    <el-dialog
        :visible.sync="dialogVisible"
        title="用户管理"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        width="450px"
    >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="formData.username"/>
            </el-form-item>
            <el-form-item label="角色" prop="roleIds">
                <el-tree
                    ref="treeRef"
                    :data="roleData"
                    :props="roleProps"
                    show-checkbox
                    height="200"
                    :default-checked-keys="defaultCheckedKeys"
                    :check-strictly="true"
                    node-key="id"
                />
            </el-form-item>

            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="formData.mobile"/>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email"/>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark"/>
            </el-form-item>

            <el-form-item>
                <el-popconfirm title="确定保存吗？" @onConfirm="submitForm(this)">
                    <el-button slot="reference" type="primary">保存</el-button>
                </el-popconfirm>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import {AdminApi} from '@/api/system/admin'
import {RoleApi} from '@/api/system/RoleApi'
import {Common} from '@/utils/common'
import {Message} from 'element-ui'

export default {
    name: 'AdminUpdate',
    components: {},
    data() {
        return {
            formData: {
                id: 0,
                username: '',
                mobile: '',
                email: '',
                remark: '',
                roleIds: ['']
            },
            rules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 1, max: 60, message: '长度在 1 到 60 个字符', trigger: 'blur'}
                ],
                roleIds: [
                    {required: true, message: '请选择角色', trigger: 'blur'}
                ]
            },
            roleData: [],
            roleProps: {
                value: 'id',
                children: 'children',
                label: 'roleName'
            },
            dialogVisible: false,
            defaultCheckedKeys: []
        }
    },

    // 显示组件
    methods: {
        showUpdate(data) {
            const that = this

            that.dialogVisible = true

            if (that.roleData.length === 0) {
                that.getRoleList(data.roleIds)
            }

            this.$nextTick(() => {
                if (that.$refs['formRef'] !== undefined) {
                    that.$refs['formRef'].resetFields()
                    that.$refs['treeRef'].setCheckedKeys([])
                }

                if (data.id > 0) {
                    that.formData = Common.assign(that.formData, data)
                    if (this.roleData.length > 0) {
                        // 初始之前使用default-checked-keys无效
                        that.$refs['treeRef'].setCheckedKeys(data.roleIds)
                    }
                } else {
                    that.formData.id = 0
                }
            })
        },

        // 获取所有角色
        getRoleList(defaultChecked) {
            RoleApi.getAllList().then((response) => {
                this.roleData = response
                this.defaultCheckedKeys = defaultChecked // 初始时使用setCheckedKeys无效
            })
        },

        // 提交表单
        submitForm() {
            const that = this
            that.formData.roleIds = this.$refs['treeRef'].getCheckedKeys(false)

            if (!that.formData.roleIds) {
                Message({
                    message: '请选择角色',
                    type: 'warning'
                })
                return false
            }

            that.$refs['formRef'].validate((valid) => {
                if (valid) {
                    if (that.formData.id > 0) {
                        AdminApi.update(that.formData)
                            .then((response) => {
                                that.dialogVisible = false
                                that.$emit('refresh')
                            })
                    } else {
                        AdminApi.insert(that.formData)
                            .then((response) => {
                                this.$alert('密码只显示一次，无法找回，请保存。<br/>密码：<b style="color:#F00;">' + response + '</b>', '登录密码', {
                                    confirmButtonText: '知道了',
                                    dangerouslyUseHTMLString: true,
                                    callback: () => {
                                        that.dialogVisible = false
                                        that.$emit('refresh')
                                    }
                                })
                            })
                    }
                }
            })
        }
    }
}
</script>
